#!/usr/bin/python3
# -*- coding: utf-8 -*-
import logging
import threading

from data import Config
from utils import Support

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
log = logging.getLogger(__name__)

mu = threading.Lock()
mu_log = threading.Lock()

isPrint = True

def logInfo(word):
    '''
    普通日志输出
    :param log:
    :param word:
    :return:
    '''
    wordLast = '{0} {1} {2} \n'.format(Support.timesFomatUseLogPrint(), '-INFO -', word)
    if mu_log.acquire(True):
        if isPrint:
            log.info(word)
        mu_log.release()
    log_file = 'log_{0}'.format(Support.timesYMD())
    saveToFileWithLock(log_file, wordLast)


def logError(word):
    '''
    报错日志输出
    :param log:
    :param word:
    :return:
    '''
    wordLast = '{0} {1} {2} \n'.format(Support.timesFomatUseLogPrint(), '-Error -', word)
    if mu_log.acquire(True):
        if isPrint:
            log.error(word)
        mu_log.release()
    log_file = 'log_{0}'.format(Support.timesYMD())
    saveToFileWithLock(log_file, wordLast)


def logWarning(word):
    '''
    告警日志输出
    :param log:
    :param word:
    :return:
    '''
    wordLast = '{0} {1} {2} \n'.format(Support.timesFomatUseLogPrint(), '-Warn -', word)
    if mu_log.acquire(True):
        if isPrint:
            log.warning(word)
        mu_log.release()
    log_file = 'log_{0}'.format(Support.timesYMD())
    saveToFileWithLock(log_file, wordLast)


def saveToFile(log_file, word):
    '''
    保存日志到本地
    :param log_file:
    :param word:
    :return:
    '''
    file = open('{0}{1}'.format(Config.log_path, log_file), 'a+')
    try:
        file.write(str(word))
        file.flush()
    finally:
        file.close()


def saveToFileWithLock(log_file, word):
    if mu.acquire(True):
        saveToFile(log_file, word)
        mu.release()
